<template>
  <div class="app-container">
    <!-- 功能区 -->
    <el-card class="operate-container" shadow="never">
      <el-form :inline="true" :model="listQuery" @submit.native.prevent>
        <el-form-item label="用户名:" class="form-item">
          <el-input v-model="listQuery.userName" class="filter-item" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item class="form-item">
          <el-button type="primary" size="mini" icon="el-icon-search" @click="getList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <div class="table_content">
      <div class="btn-btm">
        <el-button type="primary" plain size="mini" icon="el-icon-plus" @click="handleAdd">添加</el-button>
      </div>
      <!--表格渲染-->
      <el-table ref="table" v-loading="loading" :data="list" style="width: 100%;" border
                :header-cell-style="{background: '#F8F8F9',padding: '6px 0 !important',color: '#515a6e'}">
        <af-table-column prop="userName" fixed="left" label="用户名" />
        <af-table-column prop="userRole" label="所属角色" />
        <af-table-column prop="department" label="所属部门" />
        <af-table-column prop="realName" label="真实姓名" />
        <af-table-column prop="userType" label="用户类型">
          <template slot-scope="scope">
            {{{'0':'系统管理员','1':'业务员','2':'审批员','3':'监督员','4':'日志管理员'}[scope.row.userType]}}
          </template>
        </af-table-column>
        <af-table-column prop="email" label="邮箱" />
        <af-table-column prop="phone" label="电话" />
        <af-table-column prop="isStop" label="是否停用" >
          <template slot-scope="scope">
          <span :style="{color: scope.row.isStop ==0 ?'#409EFF':'#CC3333'}">
            {{{'0':'使用','1':'停用'}[scope.row.isStop]}}
          </span>
          </template>
        </af-table-column>
        <af-table-column prop="isLocked" label="是否锁住" >
          <template slot-scope="scope">
          <span :style="{color: scope.row.isLocked ==0 ?'#409EFF':'#CC3333'}">
            {{{'0':'未锁住','1':'已锁住'}[scope.row.isLocked]}}
          </span>
          </template>
        </af-table-column>
        <af-table-column prop="logined" label="是否登录过">
          <template slot-scope="scope">
            {{{'0':'未登录过','1':'已登录过'}[scope.row.logined]}}
          </template>
        </af-table-column>
        <af-table-column prop="remark" label="备注" />
        <el-table-column prop="timeLastLogin" label="最后登录时间" min-width="150"/>
        <af-table-column prop="errorTimes" label="错误次数"/>
        <el-table-column prop="timeLocked" label="锁住时间" min-width="150"/>
        <el-table-column prop="timeAdd" label="创建时间" min-width="150"/>
        <el-table-column prop="timeModify" label="修改时间" min-width="150"/>
        <af-table-column align="center" fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button class="btn" type="text" size="small"
                       @click="handleEdit(scope.$index,scope.row)">编辑</el-button>
            <el-popover
              placement="top"
              width="200"
              trigger="manual"
              :ref="'popover-' + scope.row.id">
              <p>确定删除该数据吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="mini" type="text" @click="$refs[`popover-` + scope.row.id].doClose()">取消</el-button>
                <el-button type="primary" size="mini" @click="handleDel(scope.$index,scope.row)">确定</el-button>
              </div>
              <el-button class="btn" type="text" size="small" slot="reference"
                         @click="$refs[`popover-` + scope.row.id].doShow()">删除</el-button>
            </el-popover>
            <el-dropdown trigger="click">
              <el-button type="text" size="small" >更多</el-button>
              <el-dropdown-menu slot="dropdown">
                  <span @click="allocationEdit(scope.$index,scope.row)">
                    <el-dropdown-item>分配角色</el-dropdown-item>
                  </span>
                <!--v-if="scope.row.fistFlag == 0"-->
                <span @click="pwddit(scope.$index,scope.row)">
                    <el-dropdown-item>重置密码</el-dropdown-item>
                  </span>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </af-table-column>
      </el-table>

      <!--分页-->
      <pagination v-show="total>0" :total="total"
                  :page.sync="listQuery.pageNum"
                  :limit.sync="listQuery.pageSize"
                  @pagination="getList" />
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="120px" :rules="editFormRules" ref="editForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName" class="form-item">
              <el-input v-model="editForm.userName" placeholder="用户名称" :disabled="dialogStatus != 'create'" class="filter-item"></el-input>
            </el-form-item>
            <el-form-item label="所属部门" prop="department" class="form-item">
              <el-select v-model="editForm.department" placeholder="请选择" ref="selectReport"
                         popper-class="select-popper" class="form-select"
                         :popper-append-to-body="false">
                <el-option
                  :value="editForm.orgID"
                  :label="editForm.orgName"
                  style="
                width: 450px;
                height: 200px;
                overflow: auto;
                background-color: #fff;
              ">
                  <el-tree
                    :data="orgOptions"
                    :props="{value: 'orgID',label: 'orgName',}"
                    @node-click="handleNodeClick"
                  ></el-tree>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="真实姓名" prop="realName" class="form-item">
              <el-input v-model="editForm.realName" placeholder="真实姓名" class="filter-item"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone" class="form-item">
              <el-input v-model="editForm.phone" placeholder="电话" class="filter-item"></el-input>
            </el-form-item>
            <el-form-item label="登录密码" prop="password" class="form-item" v-if="dialogStatus == 'create'">
              <el-input type="password" v-model="editForm.password"
                        auto-complete="new-password"
                        placeholder="登录密码" class="filter-item"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPwd" class="form-item" v-if="dialogStatus != 'update'">
              <el-input type="password" v-model="editForm.confirmPwd"
                        auto-complete="new-password"
                        placeholder="确认密码" class="filter-item"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="userType" class="form-item">
              <el-select placeholder="请选择" style="width:100%;" clearable v-model="editForm.userType"
                         class="form-select" :popper-append-to-body="false" popper-class="select-popper">
                <el-option :value="0" label="系统管理员"></el-option>
                <el-option :value="1" label="业务员"></el-option>
                <el-option :value="2" label="审批员"></el-option>
                <el-option :value="3" label="监督员"></el-option>
                <el-option :value="4" label="日志管理员"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="所属角色" prop="userRole" class="form-item" v-if="editForm.userType==1">
              <el-input v-model="editForm.userRole" placeholder="所属角色" class="filter-item"></el-input>
            </el-form-item>
            <el-form-item label="帐号使用状态" prop="isStop" class="form-item" v-if="dialogStatus == 'update'">
              <el-radio-group v-model="editForm.isStop">
                <el-radio :label="0">使用</el-radio>
                <el-radio :label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" class="form-item">
              <el-input v-model="editForm.email" placeholder="邮箱" class="filter-item"></el-input>
            </el-form-item>
            <el-form-item label="备注信息" prop="remark" class="form-item">
              <el-input v-model="editForm.remark" type="textarea"
                        :autosize="{ minRows: 2, maxRows: 4}"
                        autosize placeholder="备注信息" class="filter-item"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="dialogFormVisible=false">取消</el-button>
        <el-button type="primary" size="mini" @click="createData">{{dialogStatus == 'create'?'添加':'编辑'}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="dialogFRoleVisible" :close-on-click-modal="false" width="35%">
      <el-form :model="roleForm" label-width="120px" :rules="roleFormRules" ref="roleForm">
        <el-form-item label="角色" prop="roleIds" class="form-item">
          <el-select placeholder="请选择" style="width:100%;" clearable v-model="roleForm.roleIds"
                     class="form-select" :popper-append-to-body="false" popper-class="select-popper">
            <el-option v-for="item in roleList" :value="item.id" :label="item.name" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="dialogFRoleVisible=false">取消</el-button>
        <el-button type="primary" size="mini" @click="createRoleData">提交</el-button>
      </div>
    </el-dialog>

    <el-dialog title="重置密码" :visible.sync="dialogPwdVisible" :close-on-click-modal="false" width="35%">
      <el-form :model="pwdForm" label-width="120px" :rules="pwdFormRules" ref="pwdForm">
        <el-form-item label="登录密码" prop="defaultPwd" class="form-item">
          <el-input type="password" v-model="pwdForm.defaultPwd"
                    auto-complete="new-password"
                    placeholder="登录密码" class="filter-item"></el-input>
        </el-form-item>
        <el-form-item label="二次确认密码" prop="confirmPwd" class="form-item">
          <el-input type="password" v-model="pwdForm.confirmPwd"
                    auto-complete="new-password"
                    placeholder="要与登录密码保持一致" class="filter-item"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="dialogPwdVisible=false">取消</el-button>
        <el-button type="primary" size="mini" @click="updateRoleData">提交</el-button>
      </div>
    </el-dialog>

    <amend-pwd v-if="fistFlag == 0"></amend-pwd>
  </div>
</template>

<script>
  import { doPost, doGet, doFile, orglistChild } from '@/api/index'
  import { mapGetters } from 'vuex'
  import Pagination from '@/components/Pagination/index'

  export default {
    components: {
      Pagination
    },
    computed: {
      ...mapGetters([
        'sidebar',
        'avatar',
        'name',
        'perms',
        'fistFlag',
        'userForm'
      ])
    },
    data() {
      const validatePass = (rule, value, callback) => {
        let str = /^[a-zA-Z]{1}([a-zA-Z0-9]|[._]){4,19}$/;
        if (!str.test(value)) {
          callback(new Error('只能输入5-20个以字母开头、可带数字、“_”、“.”的字串'))
        } else {
          callback()
        }
      }
      const validatePass1 = (rule, value, callback) => {
        if (value != this.editForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
      }
      const validatePass2 = (rule, value, callback) => {
        if (value != this.pwdForm.defaultPwd) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      const validatePhone = (rule, value, callback) => {
        const regExp = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
        if (!regExp.test(value)) {
          callback(new Error('请输入正确的手机号'))
        } else {
          callback()
        }
      }
      return {
        listQuery: {
          userName: '',
          pageNum: 1,
          pageSize: 10
        },
        list: [],
        total: 0,
        loading: true,
        editForm: {
          isStop: '',
          department: '',
          password: '',
          userName: '',
          userType: '',
          email: '',
          phone: '',
          realName: '',
          remark: '',
          userRole: '',
          confirmPwd: '',
          logined: ''
        },
        editFormRules: {
          userName: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
          userType: [{ required: true, message: '用户类型不能为空', trigger: 'blur' }],
          password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
          email: [{ type: 'email', message: '请输入正确的邮箱', trigger: 'blur'}],
          // phone: [{ validator: validatePhone, trigger: 'blur'}],
          confirmPwd: [
            { required: true, message: '确认密码不能为空', trigger: 'blur' },
            { validator: validatePass1, trigger: 'blur' }
          ],
        },
        dialogStatus: '',
        textMap:{
          update: '编辑',
          create: '新增'
        },
        dialogFormVisible: false,
        options: [],
        srcList: [],
        roleForm: {
          roleIds: '',
          userId: ''
        },
        roleFormRules: {
          roleIds: [{ required: true, message: '请选择角色', trigger: 'blur'}]
        },
        dialogFRoleVisible: false,
        roleList: [],
        pwdForm: {
          defaultPwd: '',
          confirmPwd: '',
          id: '',
        },
        pwdFormRules: {
          defaultPwd: [{ required: true, message: '登录密码不能为空', trigger: 'blur' }],
          confirmPwd: [{ required: true, message: '二次确认密码不能为空', trigger: 'blur' },
            { validator: validatePass2, trigger: 'blur' }],
        },
        dialogPwdVisible: false,
        orgOptions: [],
      };
    },
    created: function() {
      this.getList();
      this.orgGetList()
    },
    methods: {
      //获部门列表
      orgGetList() {
        orglistChild().then(res=> {
          this.orgOptions = res.data
        }).catch(error => {
          this.orgOptions = []
        })
      },
      getList() {
        this.loading = true
        doPost('user/page',this.listQuery).then(res => {
          this.loading = false
          this.list = res.data.list
          this.total = res.data.total
        }).catch(error => {
          this.list = []
          this.total = 0
          this.loading = false
        })
      },
      //添加
      handleAdd() {
        this.dialogFormVisible = true
        this.dialogStatus = 'create'
        this.editForm = {
          isStop: 0,
          orgID: '',
          password: '',
          userName: '',
          userType: '',
          email: '',
          phone: '',
          realName: '',
          remark: '',
          confirmPwd: '',
          userRole: '',
          logined: 0,
          isLocked: 0
        }
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      // 分配角色
      allocationEdit(index, row) {
        this.dialogFRoleVisible = true
        let idS = [];
        doPost('user/getRole/' + row.id).then(res => {
          for (let item of res.data) {idS.push(item.id)}
        }).catch(error => {})
        this.roleForm = {
          roleIds: idS,
          userId: row.id
        }
        doPost('role/listAll').then(res => {
          this.roleList = res.data
        }).catch(error => {
          this.roleList = []
        })
      },
      //提交角色
      createRoleData() {
        this.$refs['roleForm'].validate(valid => {
          if (valid) {
            doPost('user/updaterole', this.roleForm).then(res => {
              if(res.code == 200) {
                this.getList()
                this.dialogFRoleVisible = false
                this.$message.success({
                  message: '提交成功',
                  type: 'success'
                })
              } else {
                this.$message.error(res.message)
              }
            }).catch(error => {
              this.$message.error(error.message)
            })
          }
        })
      },
      //重置密码
      pwddit(index, row) {
        this.dialogPwdVisible = true
        this.pwdForm = {
          defaultPwd: '',
          confirmPwd: '',
          id: row.id,
        }
        this.$nextTick(() => {
          this.$refs['pwdForm'].clearValidate()
        })
        /*let than = this
        this.$confirm('确认要重置 "' + row.userName + '" 密码吗？','提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          doPost('user/resetpwd/'+row.id).then(res => {
            if (res.code == 200) {
              than.$message.success({
                message: '重置密码成功',
                type: 'success'
              })
            } else {
              than.$message.error(res.message)
            }
          }).catch(error => {
            than.$message.error(error.message)
          })
        }).catch(() => {});*/
      },
      //提交密码
      updateRoleData() {
        this.$refs['pwdForm'].validate(valid => {
          if (valid) {
            doPost('user/resetpwd',this.pwdForm).then(res => {
              if (res.code == 200) {
                this.dialogPwdVisible = false
                this.$message.success({
                  message: '重置密码成功',
                  type: 'success'
                })
              } else {
                this.$message.error(res.message)
              }
            }).catch(error => {
              this.$message.error(error.message)
            })
          }
        })
      },
      //  修改
      handleEdit(index,row) {
        if (row) {
          for (var key in row) {
            if (row[key] == null || typeof(row[key]) === "undefined" || row[key] == undefined) {
              // delete row[key];
              row[key] = ''
            }
          }
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.editForm = Object.assign({}, row)
        /*this.editForm = {
          email: row.email,
          icon: row.icon,
          id: row.id,
          note: row.note,
          password: row.password,
          status: row.status,
          userType: row.userType,
          username: row.username,
        }*/
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
        })
      },
      createData() {
        this.$refs.editForm.validate(valid => {
          if (valid) {
            doPost(`user/${this.dialogStatus == 'create' ? 'add' : 'update'}`, this.editForm).then(res => {
              if (res.code == 200) {
                this.getList()
                this.$message.success({
                  message: this.dialogStatus == 'create'?'添加成功':'修改成功',
                  type: 'success'
                })
                this.dialogFormVisible = false
              } else {
                this.$message.error(res.message)
              }
            }).catch(error => {
              this.$message.error(error.message)
            })
          }
        })
      },
      //  删除
      handleDel(index,row) {
        doPost('user/delete/'+row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.list.splice(index, 1)
            this.total--
            this.$refs[`popover-` + row.id].doClose()
          }).catch(error => {
            this.$refs[`popover-` + row.id].doClose()
            this.$message.error(error.message)
        })
      },
      // 选择部门
      handleNodeClick(val) {
        this.$set(this.editForm, "orgID", val.orgID);
        this.$set(this.editForm, "department", val.orgName);
        if (!val.children || val.children.length == 0) {
          this.$refs.selectReport.blur();
        }
      },
    }
  };
</script>

<style lang="scss" scoped>
  .avatar-uploader /deep/.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 145px;
    height: 145px;
    line-height: 140px;
    text-align: center;
  }
  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>
